// 聊天API服务

import type { 
  ChatItem, 
  ChatMessage, 
  UserStats, 
  ChatCreateRequest, 
  ChatUpdateRequest,
  ChatListResponse,
  ChatResponse,
  UserStatsResponse
} from '@/types/chat'

class ChatService {
  private baseURL = '/api'
  
  private async request<T>(endpoint: string, options?: RequestInit): Promise<T> {
    const token = localStorage.getItem('token')
    
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        ...options?.headers,
      },
    })

    if (!response.ok) {
      const error = await response.text()
      throw new Error(`API Error: ${response.status} - ${error}`)
    }

    return response.json()
  }

  // 获取聊天列表
  async getChats(params?: {
    limit?: number
    cursor?: string
    search?: string
    pinned?: boolean
  }): Promise<ChatListResponse> {
    const searchParams = new URLSearchParams()
    
    if (params?.limit) searchParams.append('limit', params.limit.toString())
    if (params?.cursor) searchParams.append('cursor', params.cursor)
    if (params?.search) searchParams.append('search', params.search)
    if (params?.pinned !== undefined) searchParams.append('pinned', params.pinned.toString())

    return this.request<ChatListResponse>(
      `/chats?${searchParams.toString()}`
    )
  }

  // 获取单个聊天
  async getChat(chatId: string): Promise<ChatResponse> {
    return this.request<ChatResponse>(`/chats/${chatId}`)
  }

  // 创建新聊天
  async createChat(data: ChatCreateRequest): Promise<ChatResponse> {
    return this.request<ChatResponse>('/chats', {
      method: 'POST',
      body: JSON.stringify(data),
    })
  }

  // 更新聊天
  async updateChat(chatId: string, data: ChatUpdateRequest): Promise<ChatResponse> {
    return this.request<ChatResponse>(`/chats/${chatId}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    })
  }

  // 删除聊天
  async deleteChat(chatId: string): Promise<void> {
    await this.request<void>(`/chats/${chatId}`, {
      method: 'DELETE',
    })
  }

  // 批量删除聊天
  async deleteChats(chatIds: string[]): Promise<void> {
    await this.request<void>('/chats/batch', {
      method: 'DELETE',
      body: JSON.stringify({ chatIds }),
    })
  }

  // 获取聊天消息
  async getChatMessages(chatId: string, params?: {
    limit?: number
    cursor?: string
  }): Promise<{
    messages: ChatMessage[]
    hasMore: boolean
    nextCursor?: string
  }> {
    const searchParams = new URLSearchParams()
    
    if (params?.limit) searchParams.append('limit', params.limit.toString())
    if (params?.cursor) searchParams.append('cursor', params.cursor)

    return this.request(`/chats/${chatId}/messages?${searchParams.toString()}`)
  }

  // 发送消息
  async sendMessage(chatId: string, data: {
    content: string
    type: 'text' | 'image'
    parentMessageId?: string
  }): Promise<{
    message: ChatMessage
  }> {
    return this.request(`/chats/${chatId}/messages`, {
      method: 'POST',
      body: JSON.stringify(data),
    })
  }

  // 获取用户统计
  async getUserStats(period?: 'day' | 'week' | 'month' | 'year'): Promise<UserStatsResponse> {
    const searchParams = new URLSearchParams()
    if (period) searchParams.append('period', period)

    return this.request<UserStatsResponse>(
      `/user/stats?${searchParams.toString()}`
    )
  }

  // 导出聊天记录
  async exportChats(params?: {
    chatIds?: string[]
    format?: 'json' | 'markdown' | 'txt'
    includeImages?: boolean
  }): Promise<Blob> {
    const response = await fetch(`${this.baseURL}/chats/export`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : '',
      },
      body: JSON.stringify(params || {}),
    })

    if (!response.ok) {
      throw new Error(`Export failed: ${response.status}`)
    }

    return response.blob()
  }

  // 分享聊天
  async shareChat(chatId: string, options?: {
    expiresIn?: number // 过期时间（秒）
    password?: string
    allowCopy?: boolean
  }): Promise<{
    shareUrl: string
    shareId: string
    expiresAt?: string
  }> {
    return this.request(`/chats/${chatId}/share`, {
      method: 'POST',
      body: JSON.stringify(options || {}),
    })
  }

  // 搜索聊天
  async searchChats(query: string, params?: {
    limit?: number
    offset?: number
    type?: 'text' | 'image'
    dateRange?: {
      start: string
      end: string
    }
  }): Promise<{
    chats: ChatItem[]
    messages: ChatMessage[]
    total: number
  }> {
    return this.request('/chats/search', {
      method: 'POST',
      body: JSON.stringify({
        query,
        ...params,
      }),
    })
  }

  // 获取聊天模板
  async getChatTemplates(): Promise<{
    templates: Array<{
      id: string
      title: string
      description: string
      category: string
      prompt: string
      variables: string[]
    }>
  }> {
    return this.request('/chats/templates')
  }

  // 从模板创建聊天
  async createChatFromTemplate(templateId: string, variables: Record<string, string>): Promise<ChatResponse> {
    return this.request('/chats/from-template', {
      method: 'POST',
      body: JSON.stringify({
        templateId,
        variables,
      }),
    })
  }

  // 获取聊天标签
  async getChatTags(): Promise<{
    tags: Array<{
      id: string
      name: string
      color: string
      count: number
    }>
  }> {
    return this.request('/chats/tags')
  }

  // 为聊天添加标签
  async addChatTags(chatId: string, tagIds: string[]): Promise<void> {
    await this.request(`/chats/${chatId}/tags`, {
      method: 'POST',
      body: JSON.stringify({ tagIds }),
    })
  }

  // 移除聊天标签
  async removeChatTags(chatId: string, tagIds: string[]): Promise<void> {
    await this.request(`/chats/${chatId}/tags`, {
      method: 'DELETE',
      body: JSON.stringify({ tagIds }),
    })
  }

  // 获取聊天分析
  async getChatAnalytics(chatId: string): Promise<{
    messageCount: number
    tokenCount: number
    averageResponseTime: number
    topicAnalysis: Array<{
      topic: string
      confidence: number
    }>
    sentimentAnalysis: {
      positive: number
      neutral: number
      negative: number
    }
  }> {
    return this.request(`/chats/${chatId}/analytics`)
  }
}

// 创建单例实例
export const chatService = new ChatService()

// 导出类型
export type { ChatService }
export default chatService
